package cn.com.anypay.manager.controller.auth;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import java.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.anypay.manager.bean.AlipayAppConfig;
import cn.com.anypay.manager.bean.WxAppConfig;
import cn.com.anypay.manager.service.UserAuthService;

/**
 * 用户授权控制器
 * 处理支付宝、微信等第三方平台的用户授权
 */
@RestController
@RequestMapping("/api/auth")
public class UserAuthController {
    private static final Logger log = LoggerFactory.getLogger(UserAuthController.class);

    @Autowired
    @Qualifier("alipayAppConfig")
    private AlipayAppConfig appConfig;

    @Autowired
    @Qualifier("wxPayMpConfig")
    private WxAppConfig mpConfig;

    @Autowired
    @Qualifier("alipayUserAuthServiceImpl")
    private UserAuthService alipayUserAuthService;

    @Autowired
    @Qualifier("wxpayUserAuthServiceImpl")
    private UserAuthService wxpayUserAuthService;

    /**
     * 生成支付宝授权链接
     */
    @GetMapping("/alipay/url")
    public Map<String, String> generateAlipayAuthUrl(@RequestParam String redirectUri) {
        try {
            log.info("=== 生成支付宝授权链接开始 ===");
            log.info("回调地址: {}", redirectUri);

            String authUrl = alipayUserAuthService.buildAuthUrl(appConfig.getAppId(), redirectUri);

            log.info("生成的授权链接: {}", authUrl);
            return Map.of("authUrl", authUrl);
        } catch (Exception e) {
            log.error("生成授权链接失败: {}", e.getMessage(), e);
            throw new RuntimeException("生成授权链接失败", e);
        }
    }

    /**
     * 获取支付宝用户ID
     */
    @PostMapping("/alipay/user")
    public Map<String, Object> getAlipayUserId(@RequestBody Map<String, String> params) {
        try {
            log.info("=== 获取支付宝用户ID开始 ===");
            String authCode = params.get("authCode");
            log.info("授权码: {}", authCode);

            Map<String, Object> tokenInfo = alipayUserAuthService.exchangeAuthCodeForToken(
                appConfig.getAppId(),
                authCode,
                appConfig.getPrivateKey()
            );

            String userId = (String) tokenInfo.get("user_id");
            String accessToken = (String) tokenInfo.get("access_token");
            String refreshToken = (String) tokenInfo.get("refresh_token");
            Integer expiresIn = (Integer) tokenInfo.get("expires_in");

            log.info("获取用户ID成功: userId={}, accessToken={}, expiresIn={}",
                userId, accessToken, expiresIn);

            return Map.of(
                "code", 0,
                "message", "success",
                "data", Map.of(
                    "userId", userId,
                    "accessToken", accessToken,
                    "refreshToken", refreshToken,
                    "expiresIn", expiresIn
                )
            );
        } catch (Exception e) {
            log.error("获取支付宝用户ID失败: {}", e.getMessage(), e);
            return Map.of(
                "code", -1,
                "message", "获取支付宝用户ID失败: " + e.getMessage()
            );
        }
    }

    /**
     * 生成微信授权链接
     */
    @GetMapping("/wechat/url")
    public Map<String, String> generateWechatAuthUrl(@RequestParam String redirectUri) {
        try {
            log.info("=== 生成微信授权链接开始 ===");
            log.info("回调地址: {}", redirectUri);

            String authUrl = wxpayUserAuthService.buildAuthUrl(mpConfig.getAppId(), redirectUri);

            log.info("生成的授权链接: {}", authUrl);
            return Map.of("authUrl", authUrl);
        } catch (Exception e) {
            log.error("生成微信授权链接失败: {}", e.getMessage(), e);
            throw new RuntimeException("生成微信授权链接失败", e);
        }
    }

    /**
     * 获取微信用户OpenID
     */
    @PostMapping("/wechat/user")
    public Map<String, Object> getWechatOpenId(@RequestBody Map<String, String> params) {
        try {
            log.info("=== 获取微信用户OpenID开始 ===");
            String code = params.get("code");
            log.info("授权码: {}", code);

            Map<String, Object> tokenInfo = wxpayUserAuthService.exchangeAuthCodeForToken(
                mpConfig.getAppId(),
                code,
                mpConfig.getSecret()
            );

            String openId = (String) tokenInfo.get("openid");
            String accessToken = (String) tokenInfo.get("access_token");
            String refreshToken = (String) tokenInfo.get("refresh_token");
            Integer expiresIn = (Integer) tokenInfo.get("expires_in");
            String scope = (String) tokenInfo.get("scope");

            log.info("获取OpenID成功: openId={}, accessToken={}, expiresIn={}",
                openId, accessToken, expiresIn);

            return Map.of(
                "code", 0,
                "message", "success",
                "data", Map.of(
                    "openId", openId,
                    "accessToken", accessToken,
                    "refreshToken", refreshToken,
                    "expiresIn", expiresIn,
                    "scope", scope
                )
            );
        } catch (Exception e) {
            log.error("获取微信用户OpenID失败: {}", e.getMessage(), e);
            return Map.of(
                "code", -1,
                "message", "获取微信用户OpenID失败: " + e.getMessage()
            );
        }
    }
}
